<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-pink-500 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <MessageCircle class="w-8 h-8 text-white" />
          </div>
          <CardTitle class="text-2xl text-slate-800">{{
            t("wordAssociationTest.testTitle")
          }}</CardTitle>
          <p class="text-slate-600 mt-2">
            {{ t("wordAssociationTest.testDescription") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div
            class="bg-gradient-to-r from-pink-50 to-rose-50 rounded-xl p-6 border border-pink-100"
          >
            <h3
              class="font-semibold text-pink-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t("wordAssociationTest.instructionsTitle") }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span class="step-number">1</span>
                <p>{{ t("wordAssociationTest.instruction1") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">2</span>
                <p>{{ t("wordAssociationTest.instruction2") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">3</span>
                <p>{{ t("wordAssociationTest.instruction3") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">4</span>
                <p>
                  <strong>{{
                    t("wordAssociationTest.instruction4Important")
                  }}</strong>
                </p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">5</span>
                <p>{{ t("wordAssociationTest.instruction5") }}</p>
              </div>
            </div>
          </div>
          <div class="grid md:grid-cols-2 gap-4">
            <div class="info-box from-pink-50 to-pink-100 border-pink-200">
              <div class="info-box-title text-pink-600">5</div>
              <div class="info-box-body">
                {{ t("wordAssociationTest.rounds") }}
              </div>
            </div>
            <div class="info-box from-rose-50 to-rose-100 border-rose-200">
              <div class="info-box-title text-rose-600">45</div>
              <div class="info-box-body">
                {{ t("wordAssociationTest.secondsPerRound") }}
              </div>
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-pink-500 to-rose-500 hover:from-pink-600 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
            size="lg"
            @click="handleStartTest"
          >
            {{ t("wordAssociationTest.startButton") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div v-else-if="stage === 'test'" class="max-w-4xl mx-auto space-y-6">
    <transition name="slide-down">
      <div
        v-if="showFeedback"
        class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50"
      >
        <Card :class="['text-white border-0 shadow-lg', feedbackClass]">
          <CardContent class="py-2 px-4">
            <div class="flex items-center gap-2">
              <CheckCircle class="w-4 h-4" />
              <span class="font-semibold">{{ feedbackMessage }}</span>
            </div>
          </CardContent>
        </Card>
      </div>
    </transition>

    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4">
        <Badge
          class="bg-pink-100 text-pink-700 border-pink-300"
          variant="outline"
          >{{ t("wordAssociationTest.round") }} {{ currentRound + 1 }} /
          {{ MAX_ROUNDS }} {{ t("wordAssociationTest.round") }}
        </Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold"
            >{{ totalScore }} {{ t("wordAssociationTest.scoreUnit") }}</span
          >
        </div>
      </div>
      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500" />
        <span
          :class="[
            'font-mono text-lg font-bold',
            timeLeft <= 10 ? 'text-red-500' : 'text-slate-700',
          ]"
          >{{ timeLeft }}</span
        >
      </div>
    </div>

    <Progress :model-value="((45 - timeLeft) / 45) * 100" class="h-2" />

    <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-lg">
      <CardContent class="p-8">
        <div class="text-center mb-8">
          <div
            class="text-6xl font-bold bg-gradient-to-r from-pink-500 to-rose-500 bg-clip-text text-transparent mb-4"
          >
            {{ currentPrompt }}
          </div>
          <p class="text-slate-600">
            {{
              t("wordAssociationTest.promptInstruction", {
                promptWord: String(currentPrompt),
              })
            }}
          </p>
          <p class="text-sm text-slate-500 mt-1">
            {{ t("wordAssociationTest.hint") }}
          </p>
        </div>
        <div class="max-w-md mx-auto space-y-4">
          <div class="flex gap-2">
            <Input
              ref="inputRef"
              :value="currentInput"
              class="text-lg px-4 py-3 border-pink-300 focus:border-pink-500"
              :placeholder="t('wordAssociationTest.inputPlaceholder')"
              @input="currentInput = $event.target.value"
              @keydown.enter="handleWordSubmit"
            />
            <Button
              :disabled="!currentInput.trim()"
              class="bg-gradient-to-r from-pink-500 to-rose-500 hover:from-pink-600 hover:to-rose-600 px-6"
              @click="handleWordSubmit"
              >{{ t("wordAssociationTest.submitButton") }}
            </Button>
          </div>
        </div>
        <div v-if="currentRoundWords.length > 0" class="mt-8">
          <h3 class="text-sm font-semibold text-slate-600 mb-4">
            {{ t("wordAssociationTest.wordsEnteredThisRound") }} ({{
              currentRoundWords.length
            }}
            {{ t("wordAssociationTest.wordUnit") }})：
          </h3>
          <div class="flex flex-wrap gap-2">
            <transition-group name="list">
              <div
                v-for="chain in currentRoundWords"
                :key="chain.id"
                :class="['word-tag', wordTagClass(chain.points)]"
              >
                <span class="text-slate-700">{{ chain.word }}</span>
                <span
                  :class="['ml-2 font-semibold', wordScoreClass(chain.points)]"
                  >+{{ chain.points }}</span
                >
              </div>
            </transition-group>
          </div>
        </div>
      </CardContent>
    </Card>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition appear name="fade">
      <Card class="bg-white/90 backdrop-blur-sm border-pink-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-pink-500 to-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Trophy class="w-10 h-10 text-white" />
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{
            t("wordAssociationTest.testComplete")
          }}</CardTitle>
          <div
            class="text-6xl font-bold bg-gradient-to-r from-pink-500 to-rose-500 bg-clip-text text-transparent"
          >
            {{ results.finalScore }}
          </div>
          <p class="text-slate-600">
            {{ t("wordAssociationTest.associationScore") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div class="info-box from-pink-50 to-pink-100 border-pink-200">
              <div class="info-box-title text-pink-600">
                {{ results.totalWords }}
              </div>
              <div class="info-box-body">
                {{ t("wordAssociationTest.totalWords") }}
              </div>
            </div>
            <div class="info-box from-rose-50 to-rose-100 border-rose-200">
              <div class="info-box-title text-rose-600">
                {{ results.averageWordsPerRound }}
              </div>
              <div class="info-box-body">
                {{ t("wordAssociationTest.averageWordsPerRound") }}
              </div>
            </div>
          </div>
          <div class="space-y-3">
            <div class="result-row">
              <span class="text-slate-600">{{
                t("wordAssociationTest.creativityScore")
              }}</span
              ><span class="font-semibold text-slate-800"
                >{{ results.creativityScore }}%</span
              >
            </div>
            <div class="result-row">
              <span class="text-slate-600">{{
                t("wordAssociationTest.totalScore")
              }}</span
              ><span class="font-semibold text-slate-800"
                >{{ totalScore }} {{ t("wordAssociationTest.scoreUnit") }}</span
              >
            </div>
          </div>
          <Button
            class="w-full bg-gradient-to-r from-pink-500 to-rose-500 hover:from-pink-600 hover:to-rose-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
            @click="handleComplete"
          >
            {{ t("wordAssociationTest.viewDetails") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted, nextTick } from "vue";
import {
  MessageCircle,
  Clock,
  CheckCircle,
  Trophy,
  Star,
} from "lucide-vue-next";

const { t } = useI18n();
const emit = defineEmits(["complete"]);

// --- Constants ---
const ALL_PROMPT_WORDS = [
  "天空",
  "海洋",
  "森林",
  "火焰",
  "冰雪",
  "音乐",
  "绘画",
  "书籍",
  "电影",
  "舞蹈",
  "城市",
  "乡村",
  "山脉",
  "河流",
  "沙漠",
  "时间",
  "空间",
  "梦想",
  "现实",
  "自由"
];
const WORD_ASSOCIATIONS = {
  "天空": [
    "蓝天",
    "白云",
    "星星",
    "月亮",
    "太阳",
    "鸟",
    "飞机",
    "飞翔",
    "高",
    "广阔",
    "宇宙",
    "风",
    "雨",
    "彩虹",
    "大气"
  ],
  "海洋": [
    "大海",
    "水",
    "鱼",
    "船",
    "海浪",
    "深",
    "蓝色",
    "沙滩",
    "海鲜",
    "潜水",
    "岛屿",
    "珊瑚",
    "海豚",
    "鲸鱼",
    "潮汐"
  ],
  "森林": [
    "树",
    "绿色",
    "动物",
    "木头",
    "氧气",
    "深林",
    "自然",
    "探险",
    "寂静",
    "鸟语花香",
    "野兽",
    "树叶",
    "泥土",
    "生态"
  ],
  "火焰": [
    "火",
    "热",
    "燃烧",
    "光明",
    "红色",
    "温暖",
    "危险",
    "烟",
    "灰烬",
    "热情",
    "毁灭",
    "生命",
    "希望",
    "能量"
  ],
  "冰雪": [
    "冰",
    "雪",
    "冷",
    "白色",
    "冬天",
    "寒冷",
    "晶莹",
    "滑",
    "纯洁",
    "融化",
    "冰川",
    "雪花",
    "北极",
    "南极"
  ],
  "音乐": [
    "歌曲",
    "旋律",
    "节奏",
    "乐器",
    "唱歌",
    "跳舞",
    "艺术",
    "声音",
    "美妙",
    "情感",
    "演唱会",
    "古典",
    "流行",
    "音符"
  ],
  "绘画": [
    "画笔",
    "颜料",
    "画布",
    "艺术",
    "色彩",
    "创作",
    "美术",
    "画廊",
    "展览",
    "肖像",
    "风景",
    "抽象",
    "印象"
  ],
  "书籍": [
    "阅读",
    "知识",
    "文字",
    "故事",
    "图书馆",
    "学习",
    "智慧",
    "纸张",
    "作者",
    "小说",
    "历史",
    "科学",
    "教育"
  ],
  "电影": [
    "影院",
    "演员",
    "导演",
    "剧情",
    "屏幕",
    "爆米花",
    "娱乐",
    "故事",
    "特效",
    "科幻",
    "喜剧",
    "悲剧",
    "动画"
  ],
  "舞蹈": [
    "跳舞",
    "舞者",
    "舞台",
    "节奏",
    "动作",
    "优美",
    "艺术",
    "表演",
    "芭蕾",
    "街舞",
    "现代舞",
    "民族舞"
  ],
  "城市": [
    "高楼",
    "街道",
    "人群",
    "交通",
    "繁华",
    "现代",
    "都市",
    "建筑",
    "灯光",
    "喧嚣",
    "生活",
    "发展",
    "机遇"
  ],
  "乡村": [
    "田野",
    "农田",
    "自然",
    "宁静",
    "朴实",
    "小路",
    "炊烟",
    "星空",
    "自由",
    "简单",
    "淳朴",
    "乡愁"
  ],
  "山脉": [
    "山",
    "高",
    "雄伟",
    "攀登",
    "自然",
    "风景",
    "险峻",
    "云雾",
    "森林",
    "岩石",
    "徒步",
    "征服"
  ],
  "河流": [
    "水",
    "流动",
    "生命",
    "源头",
    "两岸",
    "船",
    "鱼",
    "清澈",
    "蜿蜒",
    "灌溉",
    "航运",
    "生态"
  ],
  "沙漠": [
    "沙",
    "干旱",
    "骆驼",
    "仙人掌",
    "荒凉",
    "寂寞",
    "戈壁",
    "绿洲",
    "探险",
    "生存",
    "酷热",
    "风沙"
  ],
  "时间": [
    "过去",
    "现在",
    "未来",
    "流逝",
    "永恒",
    "瞬间",
    "钟表",
    "岁月",
    "历史",
    "生命",
    "珍惜",
    "等待"
  ],
  "空间": [
    "维度",
    "宇宙",
    "距离",
    "广阔",
    "狭窄",
    "三维",
    "四维",
    "无限",
    "存在",
    "位置",
    "方向",
    "自由"
  ],
  "梦想": [
    "希望",
    "未来",
    "追求",
    "实现",
    "理想",
    "憧憬",
    "奋斗",
    "勇气",
    "坚持",
    "成功",
    "飞翔",
    "自由"
  ],
  "现实": [
    "真实",
    "当下",
    "生活",
    "残酷",
    "面对",
    "接受",
    "挑战",
    "努力",
    "奋斗",
    "生存",
    "理性",
    "客观"
  ],
  "自由": [
    "解放",
    "独立",
    "无拘束",
    "选择",
    "权利",
    "思想",
    "精神",
    "飞翔",
    "呼吸",
    "奔跑",
    "创造",
    "和平"
  ]
};
const SCORING_CRITERIA = {
  creative: 10,
  common: 5,
  timeBonus: 5,
  chainBonus: 15,
};

const getRandomPromptWords = () => {
  const shuffled = [...ALL_PROMPT_WORDS].sort(() => 0.5 - Math.random());
  return shuffled.slice(0, 5);
};

const checkWordRelevance = (inputWord, promptWord) => {
  const associations = WORD_ASSOCIATIONS[promptWord] || [];
  const input = inputWord.toLowerCase().trim();
  const prompt = promptWord.toLowerCase();
  if (
    associations.some(
      (word) =>
        word.toLowerCase().includes(input) || input.includes(word.toLowerCase())
    )
  )
    return {
      isRelevant: true,
      confidence: 0.9,
    };
  if (associations.some((word) => word.toLowerCase() === input))
    return { isRelevant: true, confidence: 1.0 };
  if (
    associations.some((word) => {
      const w = word.toLowerCase();
      return (
        input.length >= 2 &&
        w.length >= 2 &&
        (w.includes(input.slice(0, 2)) || input.includes(w.slice(0, 2)))
      );
    })
  )
    return { isRelevant: true, confidence: 0.6 };
  if (input.includes(prompt) || prompt.includes(input))
    return { isRelevant: true, confidence: 0.8 };
  const semanticKeywords = {
    "自然": [
      "山",
      "水",
      "树",
      "花",
      "草",
      "风",
      "雨",
      "云",
      "天",
      "地",
      "日",
      "月",
      "星",
      "海",
      "林",
      "石",
      "土"
    ],
    "情感": [
      "爱",
      "恨",
      "喜",
      "怒",
      "哀",
      "乐",
      "悲",
      "欢",
      "离",
      "合",
      "情",
      "绪",
      "心",
      "感",
      "觉"
    ],
    "抽象": [
      "时间",
      "空间",
      "概念",
      "思想",
      "理论",
      "哲学",
      "真理",
      "意义",
      "价值",
      "存在",
      "虚无"
    ],
    "具象": [
      "桌",
      "椅",
      "笔",
      "书",
      "灯",
      "房",
      "车",
      "人",
      "物",
      "事",
      "地",
      "点"
    ],
    "动作": [
      "跑",
      "跳",
      "走",
      "飞",
      "说",
      "听",
      "看",
      "做",
      "吃",
      "喝",
      "睡",
      "站",
      "坐"
    ],
    "颜色": [
      "红",
      "黄",
      "蓝",
      "绿",
      "白",
      "黑",
      "紫",
      "橙",
      "灰",
      "粉",
      "棕"
    ],
    "形状": [
      "圆",
      "方",
      "长",
      "短",
      "高",
      "矮",
      "大",
      "小",
      "宽",
      "窄",
      "扁",
      "平"
    ],
    "声音": [
      "声",
      "音",
      "响",
      "乐",
      "歌",
      "哭",
      "笑",
      "叫",
      "喊",
      "说",
      "唱"
    ],
    "味道": ["酸", "甜", "苦", "辣", "咸", "香", "臭", "鲜", "淡", "浓"],
    "触感": ["冷", "热", "软", "硬", "滑", "粗", "湿", "干", "轻", "重"],
    "职业": [
      "医生",
      "老师",
      "工人",
      "农民",
      "学生",
      "警察",
      "军人",
      "厨师",
      "司机",
      "销售",
      "会计"
    ],
    "动物": [
      "猫",
      "狗",
      "鸟",
      "鱼",
      "虎",
      "狮",
      "象",
      "马",
      "牛",
      "羊",
      "猪",
      "鸡",
      "鸭",
      "虫",
      "蛇"
    ],
    "植物": [
      "树",
      "花",
      "草",
      "叶",
      "根",
      "茎",
      "果",
      "实",
      "木",
      "竹",
      "藤"
    ],
    "食物": [
      "米",
      "面",
      "菜",
      "肉",
      "蛋",
      "奶",
      "糖",
      "盐",
      "油",
      "饭",
      "面包",
      "水果"
    ],
    "交通": [
      "车",
      "船",
      "飞机",
      "火车",
      "路",
      "桥",
      "站",
      "港",
      "机场",
      "地铁",
      "公交"
    ],
    "建筑": [
      "房",
      "屋",
      "楼",
      "塔",
      "门",
      "窗",
      "墙",
      "瓦",
      "砖",
      "梁",
      "柱"
    ],
    "工具": [
      "刀",
      "剪",
      "锤",
      "锯",
      "笔",
      "尺",
      "本",
      "电脑",
      "手机",
      "相机",
      "电视"
    ],
    "身体": [
      "头",
      "手",
      "脚",
      "眼",
      "耳",
      "鼻",
      "口",
      "身",
      "心",
      "肝",
      "肺",
      "胃"
    ],
    "家庭": [
      "家",
      "人",
      "父",
      "母",
      "子",
      "女",
      "兄",
      "弟",
      "姐",
      "妹",
      "亲",
      "爱"
    ],
    "教育": [
      "学",
      "教",
      "书",
      "笔",
      "知识",
      "学校",
      "老师",
      "学生",
      "考试",
      "毕业",
      "文凭"
    ],
    "科技": [
      "电",
      "脑",
      "网",
      "络",
      "数据",
      "信息",
      "智能",
      "机器",
      "程序",
      "代码",
      "芯片"
    ],
    "艺术": [
      "画",
      "歌",
      "舞",
      "剧",
      "美",
      "术",
      "音",
      "乐",
      "诗",
      "文",
      "影",
      "视"
    ],
    "运动": [
      "跑",
      "跳",
      "球",
      "赛",
      "健",
      "身",
      "游",
      "泳",
      "足",
      "篮",
      "排",
      "羽",
      "乒"
    ],
    "疾病": [
      "病",
      "痛",
      "医",
      "药",
      "医院",
      "医生",
      "健康",
      "治疗",
      "康复",
      "病毒",
      "细菌"
    ],
    "国家": [
      "国",
      "家",
      "城",
      "市",
      "民",
      "族",
      "政",
      "府",
      "法律",
      "经济",
      "文化",
      "历史"
    ],
    "社会": [
      "人",
      "群",
      "社",
      "会",
      "组织",
      "关系",
      "交流",
      "合作",
      "竞争",
      "发展",
      "进步"
    ],
    "哲学": [
      "思",
      "想",
      "理",
      "论",
      "道",
      "德",
      "伦",
      "理",
      "生",
      "死",
      "存",
      "在"
    ],
    "宗教": [
      "神",
      "佛",
      "教",
      "徒",
      "寺",
      "庙",
      "经",
      "典",
      "信",
      "仰",
      "灵",
      "魂"
    ],
    "军事": [
      "军",
      "队",
      "战",
      "争",
      "武",
      "器",
      "兵",
      "士",
      "将",
      "领",
      "防",
      "御"
    ],
    "金融": [
      "钱",
      "币",
      "银行",
      "投资",
      "股票",
      "基金",
      "经济",
      "市场",
      "财富",
      "债务",
      "风险"
    ],
    "法律": [
      "法",
      "律",
      "规",
      "则",
      "正",
      "义",
      "审",
      "判",
      "犯",
      "罪",
      "惩",
      "罚"
    ],
    "政治": [
      "政",
      "治",
      "权",
      "力",
      "领",
      "导",
      "民",
      "主",
      "共",
      "和",
      "党",
      "派"
    ],
    "历史": [
      "历",
      "史",
      "朝",
      "代",
      "事件",
      "人物",
      "发展",
      "变迁",
      "文明",
      "文化",
      "遗迹"
    ],
    "地理": [
      "地",
      "理",
      "山",
      "水",
      "河",
      "海",
      "湖",
      "岛",
      "洲",
      "洋",
      "陆",
      "地"
    ],
    "天文": [
      "天",
      "文",
      "星",
      "球",
      "宇宙",
      "太阳",
      "月亮",
      "行星",
      "恒星",
      "银河",
      "黑洞"
    ],
    "气象": [
      "气",
      "象",
      "风",
      "雨",
      "雪",
      "雷",
      "电",
      "晴",
      "阴",
      "云",
      "雾",
      "霜",
      "露"
    ],
    "文学": [
      "文",
      "学",
      "诗",
      "歌",
      "散",
      "文",
      "小说",
      "剧本",
      "作者",
      "读者",
      "作品"
    ],
    "心理": [
      "心",
      "理",
      "情",
      "绪",
      "思",
      "维",
      "意识",
      "潜意识",
      "梦",
      "境",
      "人格"
    ]
  };
  for (const [category, keywords] of Object.entries(semanticKeywords)) {
    const inputHasKeyword = keywords.some((key) => input.includes(key));
    const promptHasKeyword = keywords.some((key) => prompt.includes(key));
    if (inputHasKeyword && promptHasKeyword)
      return { isRelevant: true, confidence: 0.4 };
  }
  if (associations.length === 0) {
    const commonChars = [...input].filter((char) => prompt.includes(char));
    if (commonChars.length >= 1 && input.length >= 2)
      return { isRelevant: true, confidence: 0.3 };
  }
  return { isRelevant: false, confidence: 0 };
};

const stage = ref("instructions"); // 'instructions', 'test', 'results'
const currentRound = ref(0);
const allWordChains = ref([]);
const currentRoundWords = ref([]);
const currentInput = ref("");
const timeLeft = ref(45);
const totalScore = ref(0);
const roundStartTime = ref(Date.now());
const showFeedback = ref(false);
const feedbackMessage = ref("");
const promptWords = ref([]);
const inputRef = ref(null);

let timer = null;
const MAX_ROUNDS = 5;

const currentPrompt = computed(
  () => promptWords.value[currentRound.value] || ""
);

const results = computed(() => {
  if (stage.value !== "results") return {};
  const totalWords = allWordChains.value.length;
  const averageWordsPerRound = totalWords / MAX_ROUNDS;
  const maxPossibleScore = MAX_ROUNDS * 200;
  const finalScore = Math.min(
    100,
    Math.round((totalScore.value / maxPossibleScore) * 100)
  );
  const roundPerformance = Array.from({ length: MAX_ROUNDS }, (_, i) => {
    const roundWords = allWordChains.value.filter(
      (chain) => chain.round === i + 1
    );
    return {
      round: i + 1,
      wordsCount: roundWords.length,
      totalScore: roundWords.reduce((sum, chain) => sum + chain.points, 0),
      prompt: promptWords.value[i] || "",
    };
  });
  return {
    finalScore,
    totalWords,
    averageWordsPerRound,
    creativityScore: Math.round((totalScore.value / maxPossibleScore) * 100),
    roundPerformance,
  };
});

const feedbackClass = computed(() => {
  if (feedbackMessage.value.includes("❌")) return "bg-red-500"; // Assuming error messages start with ❌
  if (
    feedbackMessage.value.includes("已输入过") ||
    feedbackMessage.value.includes("无关")
  )
    return "bg-orange-500"; // Simplified check
  return "bg-green-500";
});

const wordTagClass = (points) => {
  if (points === 0)
    return "bg-gradient-to-r from-red-100 to-red-200 border-red-300";
  if (points > 15)
    return "bg-gradient-to-r from-yellow-100 to-orange-100 border-yellow-300";
  if (points > 10)
    return "bg-gradient-to-r from-pink-100 to-rose-100 border-pink-200";
  if (points > 5)
    return "bg-gradient-to-r from-blue-100 to-blue-200 border-blue-300";
  return "bg-gradient-to-r from-gray-100 to-gray-200 border-gray-300";
};

const wordScoreClass = (points) => {
  if (points === 0) return "text-red-600";
  if (points > 15) return "text-orange-600";
  if (points > 10) return "text-pink-600";
  if (points > 5) return "text-blue-600";
  return "text-gray-600";
};

const calculateWordScore = (word, timeTaken, isUnique, promptWord) => {
  const relevance = checkWordRelevance(word, promptWord);
  if (!relevance.isRelevant || !isUnique) return 0;
  let score = Math.floor(SCORING_CRITERIA.common * relevance.confidence);
  if (relevance.confidence >= 0.9) score += 10;
  else if (relevance.confidence >= 0.6) score += 5;
  if (word.length >= 4) score += 3;
  if (word.length >= 6) score += 5;
  if (
    word.includes("的") ||
    word.includes("之") ||
    word.includes("性") ||
    word.includes("化")
  )
    score += 5;
  if (timeTaken < 2000) score += SCORING_CRITERIA.timeBonus;
  else if (timeTaken < 5000)
    score += Math.floor(SCORING_CRITERIA.timeBonus / 2);
  return Math.max(0, score);
};

const handleWordSubmit = () => {
  if (!currentInput.value.trim()) return;

  const word = currentInput.value.trim();
  const timeTaken = Date.now() - roundStartTime.value;

  const isUnique = !currentRoundWords.value.some(
    (chain) => chain.word.toLowerCase() === word.toLowerCase()
  );

  const relevance = checkWordRelevance(word, currentPrompt.value);
  const points = calculateWordScore(
    word,
    timeTaken,
    isUnique,
    currentPrompt.value
  );

  const newChain = {
    id: Date.now(),
    word,
    userInput: word,
    points,
    timeTaken,
    round: currentRound.value + 1,
    prompt: currentPrompt.value,
  };

  currentRoundWords.value.push(newChain);
  allWordChains.value.push(newChain);
  totalScore.value += points;
  currentInput.value = "";
  roundStartTime.value = Date.now();

  let message = t("wordAssociationTest.feedback_points", { points });
  if (!isUnique) {
    message = t("wordAssociationTest.feedback_duplicate");
  } else if (points === 0) {
    message = t("wordAssociationTest.feedback_irrelevant", {
      word: word,
      promptWord: currentPrompt.value,
    });
  } else if (!relevance.isRelevant) {
    message = t("wordAssociationTest.feedback_low_relevance", { points });
  } else if (relevance.confidence >= 0.9) {
    message = t("wordAssociationTest.feedback_highly_relevant", { points });
  } else if (timeTaken < 2000) {
    message = t("wordAssociationTest.feedback_quick_response", { points });
  } else if (word.length >= 6) {
    message = t("wordAssociationTest.feedback_creative_word", { points });
  } else if (relevance.confidence >= 0.6) {
    message = t("wordAssociationTest.feedback_related_association", { points });
  }

  feedbackMessage.value = message;
  showFeedback.value = true;
  setTimeout(() => (showFeedback.value = false), 2000);
};

const handleRoundEnd = () => {
  if (timer) clearInterval(timer);
  if (currentRound.value < MAX_ROUNDS - 1) {
    currentRound.value++;
    currentRoundWords.value = [];
    timeLeft.value = 45;
    roundStartTime.value = Date.now();
  } else {
    stage.value = "results";
  }
};

const handleStartTest = () => {
  promptWords.value = getRandomPromptWords();
  stage.value = "test";
  roundStartTime.value = Date.now();
};

const handleComplete = () => {
  const res = results.value;
  emit("complete", {
    id: Date.now().toString(),
    testType: "word-association",
    score: res.finalScore,
    completedAt: new Date(),
    duration: MAX_ROUNDS * 45,
    details: {
      roundsCompleted: MAX_ROUNDS,
      totalWords: res.totalWords,
      averageWordsPerRound: res.averageWordsPerRound,
      creativityScore: res.creativityScore,
      totalRawScore: totalScore.value,
      roundPerformance: res.roundPerformance,
      allWords: allWordChains.value.map((c) => ({
        word: c.word,
        points: c.points,
        round: c.round,
        prompt: c.prompt,
      })),
    },
  });
};

watch([stage, currentRound], (newValues) => {
  if (timer) clearInterval(timer);
  if (newValues[0] === "test") {
    timeLeft.value = 45;
    timer = setInterval(() => {
      timeLeft.value--;
      if (timeLeft.value <= 0) {
        handleRoundEnd();
      }
    }, 1000);
    nextTick(() => inputRef.value?.$el?.focus());
  }
});

onMounted(() => {
  promptWords.value = getRandomPromptWords();
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease-out;
}

.slide-down-enter-from,
.slide-down-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: scale(0.8);
}

.step-number {
  @apply w-6 h-6 bg-pink-500 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5;
}

.info-box {
  @apply text-center p-4 bg-gradient-to-br rounded-xl border;
}

.info-box-title {
  @apply text-2xl font-bold mb-1;
}

.info-box-body {
  @apply text-sm;
}

.task-preview-box {
  @apply bg-gradient-to-br rounded-xl p-4 border;
}

.result-row {
  @apply flex justify-between items-center p-3 bg-slate-50 rounded-lg;
}

.word-tag {
  @apply border rounded-lg px-3 py-1 text-sm;
}
</style>
